package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ModelMapperUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.AlarmThresholdConfigData;
import com.ruoyi.system.domain.DeviceAlarmThreshold;
import com.ruoyi.system.domain.dto.req.DeviceAlarmThresholdReqDTO;
import com.ruoyi.system.domain.dto.resp.DeviceAlarmThresholdRespDTO;
import com.ruoyi.system.mapper.DeviceAlarmThresholdMapper;
import com.ruoyi.system.service.DeviceAlarmThresholdService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备阈值设定表(DeviceAlarmThreshold)表服务实现类
 *
 * @author panlei
 * @since 2025-02-27 15:46:58
 */
@Service
@Slf4j
public class DeviceAlarmThresholdServiceImpl implements DeviceAlarmThresholdService {
    @Resource
    private DeviceAlarmThresholdMapper deviceALarmThresholdMapper;

//    @Resource
//    private VariableDictDataMapper variableDictDataMapper;
//
//    @Resource
//    private SubDeviceMapper subDeviceMapper;

    @Resource
    private RedisCache redisCache;

    // 阈值缓存key(格式：agriculture_monitor:设备id:threshold_value)
    private static String THRESHOLD_VALUE_KEY = "agriculture_monitor:%s:threshold_value";

    /**
     * 系统启动时查询设备阈值设定表数据往redis存储，便于协议包取到阈值相关信息
     */
    @PostConstruct
    public void init() {
        log.info("begin init thresholdValue");
        try {
            saveThresholdValueToRedis();
        } catch (Exception e) {
            log.error("thresholdValue init failed", e);
        }
        log.info("end init thresholdValue");
    }

    /**
     * 存储阈值列表到redis
     */
    private void saveThresholdValueToRedis() {
        // 查询阈值列表
        List<DeviceAlarmThresholdRespDTO> list = list((DeviceAlarmThresholdReqDTO) null);
        // 使用 Stream API 将 List 按照 device_sn 分组
        Map<String, List<DeviceAlarmThresholdRespDTO>> groupedByDeviceSn = list.stream()
                .collect(Collectors.groupingBy(DeviceAlarmThresholdRespDTO::getDeviceSn));
        // 遍历设备列表分别存储redis
        groupedByDeviceSn.forEach((key, value) -> {
            // 使用 Stream API 将 groupedByDeviceSn 转换为 Map，key 为 device_sn
            String thresholdValueKey = String.format(THRESHOLD_VALUE_KEY, key);

            List<AlarmThresholdConfigData> configDataList = ModelMapperUtils.strictMapList(value, AlarmThresholdConfigData.class);
            // 存储redis
            redisCache.setCacheObject(thresholdValueKey, JSON.toJSONString(configDataList));
            log.info("thresholdValue into redis success,{}", JSON.toJSONString(configDataList));
        });
    }

    @Override
    public List<DeviceAlarmThresholdRespDTO> list(DeviceAlarmThresholdReqDTO reqDTO) {
        // 辅控设备名称
        List<DeviceAlarmThresholdRespDTO> respList = deviceALarmThresholdMapper.list(reqDTO);
        return respList;
    }

    @Override
    public void add(DeviceAlarmThresholdReqDTO reqDTO) {
        Integer count = deviceALarmThresholdMapper.selectCount(reqDTO.getDeviceSn(), reqDTO.getVariableName(), reqDTO.getAlarmThresholdType());
        if (count > 0) {
            throw new ServiceException("设备参数编码重复，请重新填写");
        }
        DeviceAlarmThreshold deviceAlarmThreshold = ModelMapperUtils.strictMap(reqDTO, DeviceAlarmThreshold.class);
        deviceAlarmThreshold.setId(IdUtils.simpleUUID());
        deviceAlarmThreshold.setCreateBy(SecurityUtils.getUsername());
        deviceAlarmThreshold.setCreateTime(new Date());
        deviceALarmThresholdMapper.insert(deviceAlarmThreshold);
        // 存储redis
        saveThresholdValueToRedis();
    }

    @Override
    public void update(DeviceAlarmThresholdReqDTO reqDTO) {
        DeviceAlarmThreshold deviceAlarmThreshold = deviceALarmThresholdMapper.queryById(reqDTO.getId());
        if (ObjectUtils.isEmpty(deviceAlarmThreshold)) {
            throw new ServiceException("修改的告警阈值不存在，请重新选择");
        }
        deviceAlarmThreshold = ModelMapperUtils.strictMap(reqDTO, DeviceAlarmThreshold.class);
        deviceAlarmThreshold.setUpdateBy(SecurityUtils.getUsername());
        deviceAlarmThreshold.setUpdateTime(new Date());
        deviceALarmThresholdMapper.update(deviceAlarmThreshold);
        // 存储redis
        saveThresholdValueToRedis();
    }

    @Override
    public Integer delete(List<String> idList) {
        deviceALarmThresholdMapper.delete(idList);
        // 存储redis
        saveThresholdValueToRedis();
        return idList.size();
    }
}

